﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.IdentityModel.Claims
Imports System.Collections.Generic

Namespace Infrastructure

    Public Class UserPrivilegesAuthorizationManager
        Inherits ClaimsAuthorizationManager
        Private ReadOnly storageRequestValidators As IEnumerable(Of IStorageRequestValidator)

        Public Sub New()
            Me.New(New IStorageRequestValidator() {New SqlAzureODataServiceRequestValidator()})
        End Sub

        Public Sub New(ByVal storageRequestValidators As IEnumerable(Of IStorageRequestValidator))
            Me.storageRequestValidators = storageRequestValidators
        End Sub

        Public Overrides Function CheckAccess(ByVal context As AuthorizationContext) As Boolean
            Dim identity = TryCast(context.Principal.Identity, IClaimsIdentity)
            If identity Is Nothing OrElse (Not identity.IsAuthenticated) Then
                Return False
            End If

            Dim nameIdentifier = identity.Claims.FirstOrDefault(Function(c) c.ClaimType = ClaimTypes.NameIdentifier)
            If nameIdentifier Is Nothing Then
                Return False
            End If

            Dim resourceUri = New Uri(context.Resource.First().Value, UriKind.RelativeOrAbsolute)
            For Each validator In Me.storageRequestValidators
                If validator.DoesRequestApply(resourceUri) Then
                    Return validator.ValidateRequest(nameIdentifier.Value, HttpContext.Current.Request)
                End If
            Next validator

            Return MyBase.CheckAccess(context)
        End Function
    End Class
End Namespace